import { MD5 } from 'crypto-js'

/**
 * 签名密钥
 */
const signatureSecret = 'dd05f1c54d63749eda95f9fa6d49v442a'

/**
 * 生成签名
 * @param params 请求参数
 * @param timestamp 时间戳
 */
export function generateSignature(params: Record<string, any> = {}, timestamp: number): string {
  // 1. 对参数按照key=value的格式，并按照参数名ASCII字典序排序
  const sortedParams = Object.keys(params)
    .sort()
    .reduce((result: Record<string, any>, key: string) => {
      // 空值不参与签名
      if (params[key] != null && params[key] !== '') {
        result[key] = params[key]
      }
      return result
    }, {})

  // 2. 拼接参数字符串
  let signStr = ''
  for (const key in sortedParams) {
    if (Object.prototype.hasOwnProperty.call(sortedParams, key)) {
      const value = sortedParams[key]
      // 如果值是对象，转换为JSON字符串
      const valueStr = typeof value === 'object' ? JSON.stringify(value) : value
      signStr += `${key}=${valueStr}&`
    }
  }

  // 3. 添加时间戳和密钥
  signStr += `timestamp=${timestamp}&${signatureSecret}`

  // 4. MD5加密
  return MD5(signStr).toString()
}

/**
 * 验证时间戳是否有效（10分钟内有效）
 * @param timestamp 时间戳
 */
export function isTimestampValid(timestamp: number): boolean {
  const now = Date.now()
  const diff = Math.abs(now - timestamp)
  return diff <= 10 * 60 * 1000 // 10分钟
}

/**
 * 生成随机字符串
 * @param length 长度
 */
export function generateNonceStr(length = 32): string {
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
  let result = ''
  for (let i = 0; i < length; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}
